package com.onitaku.dibuxodrawer;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.onitaku.dibuxodrawer.adapter.NavDrawerListAdapter;
import com.onitaku.dibuxodrawer.handler.ServiceHandler;
import com.onitaku.dibuxodrawer.model.NavDrawerItem;

public class MainActivity extends ListActivity {
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	
	
	///////////////////////////////////////////////////////////////////////
	
	private ProgressDialog pDialog;
	
//	// URL para coger el JSON
    private static String url = "http://onitaku.com/JSON/";
    
//    // Nodos JSON 
    private static final String TAG_MENU = "menu";
    private static final String TAG_ID = "id";
    private static final String TAG_TITLE = "title";
    private static final String TAG_ALIAS = "alias";
    private static final String TAG_LINK = "link";
    private static final String TAG_ICON = "icon";
    private static final String TAG_SUB = "sub";
//    
//    // menu JSONArray
    JSONArray menu = null;
 
//    // Hashmap para el ListView
    ArrayList<HashMap<String, String>> menuList;
    
   ///////////////////////////////////////////////////////////////////////

	// title nav drawer 
	private CharSequence mDrawerTitle;

	// esto es para guardar el title de la app
	private CharSequence mTitle;

	// items del slide menu
	private String[] navMenuTitles;
	private TypedArray navMenuIcons;

	private ArrayList<NavDrawerItem> navDrawerItems;
	private NavDrawerListAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		////////////////////////////////////////////////////////////////////
		
		menuList = new ArrayList<HashMap<String, String>>();
		 
        ListView lv = getListView();
        
		// Listview on item click listener
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// getting values from selected ListItem
				String title = ((TextView) view.findViewById(R.id.title))
						.getText().toString();
				String link = ((TextView) view.findViewById(R.id.link))
						.getText().toString();

				// homefragment activity
				Intent in = new Intent(getApplicationContext(),
						HomeFragment.class);
				in.putExtra(TAG_TITLE, title);
				in.putExtra(TAG_LINK, link);
				startActivity(in);

			}
		});
//
//		// Llamar tarea asíncrona para coger el json
//        
        new Getmenu().execute();
		
		////////////////////////////////////////////////////////////
        
        mTitle = mDrawerTitle = getTitle();

		// cargar items del slide menu
		navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

		// nav drawer icons desde los recursos
		navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.list);

		navDrawerItems = new ArrayList<NavDrawerItem>();

		// agregar los items nav drawer al array
		
			// Inicio
			navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));

		// Reciclar el array escrito
		navMenuIcons.recycle();

		mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

		// estableciendo el adaptador de lista de nav drawer
		
		adapter = new NavDrawerListAdapter(getApplicationContext(),
				navDrawerItems);
		mDrawerList.setAdapter(adapter);

		//permitir en la barra de acción el icono de la aplicación y comportarse como botón de cambio
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, //nav menu toggle icon
				R.string.app_name, // nav drawer open - description for accessibility
				R.string.app_name // nav drawer close - description for accessibility
		) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				// calling onPrepareOptionsMenu() to show action bar icons
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				// calling onPrepareOptionsMenu() to hide action bar icons
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			// on first time display view for first nav item
			displayView(0);
		}
	}

	/**
	 * Escuchador de los clicks del Slide menu
	 * */
	private class SlideMenuClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// display view for selected nav drawer item
			displayView(position);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// toggle nav drawer on selecting action bar app icon/title
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		// Manejar los clicks de la action bar
		switch (item.getItemId()) {
		case R.id.action_settings:
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/* *
	 * llamado cuando invalidateOptionsMenu() es disparado 
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// if nav drawer is opened, hide the action items
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	/**
	 * Diplaying fragment view for selected nav drawer list item
	 * */
	private void displayView(int position) {
		// actualizar el contenido principal reemplazando con fragments
		Fragment fragment = null;
		switch (position) {
		case 0:
			fragment = new HomeFragment();
			break;
		default:
			break;
		}

		if (fragment != null) {
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.frame_container, fragment).commit();

			// actualizar objeto seleccionado y titulo, y luego cerrar el drawer
			mDrawerList.setItemChecked(position, true);
			mDrawerList.setSelection(position);
			setTitle(navMenuTitles[position]);
			mDrawerLayout.closeDrawer(mDrawerList);
		} else {
			// error al crear el fragment
			Log.e("MainActivity", "Error in creating fragment");
		}
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	/**
	 * al usar ActionBarDrawerToggle, se debe llamar durante el
	 * onPostCreate() y onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sincroniza el estado del toggle después de producirse onRestoreInstanceState.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Aprobar cualquier cambio de configuracion drawer toggles
		mDrawerToggle.onConfigurationChanged(newConfig);
	}
	
	/////////////////////////////////////////////////////////////////////////////////
	
	/**
	 ** Async task class to get json by making HTTP call
    **/
	
	
    private class Getmenu extends AsyncTask<Void, Void, Void> {
 
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Por favor espera...");
            pDialog.setCancelable(false);
            pDialog.show();
        }
        
        
        @Override
        protected Void doInBackground(Void... arg0) {
            // Crear instancia de clase del controlador de servicio
            ServiceHandler sh = new ServiceHandler();
// 
//            // Hacer una petición de URL y obtener respuesta
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
 
            Log.d("Response: ", "> " + jsonStr);
 
            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                     
                    // Conseguir nodo array JSON
                    menu = jsonObj.getJSONArray(TAG_MENU);
 
                    // bucle a través de los elementos
                    for (int i = 0; i < menu.length(); i++) {
                        JSONObject m = menu.getJSONObject(i);
                         
                        String id = m.getString(TAG_ID);
                        String title = m.getString(TAG_TITLE);
                        String alias = m.getString(TAG_ALIAS);
                        String link = m.getString(TAG_LINK);
                        String icon = m.getString(TAG_ICON);

                        JSONObject sub = m.getJSONObject(TAG_SUB);
                      
                        // tmp hashmap para el single listmenu
                        HashMap<String, String> menu = new HashMap<String, String>();
 
                        // adding each child node to HashMap key => value
                        menu.put(TAG_ID, id);
                        menu.put(TAG_TITLE, title);
                        menu.put(TAG_ALIAS, alias);
                        menu.put(TAG_LINK, link);
 
                        // agregar elemento a la lista de menu
                        menuList.add(menu);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "No se ha podido recoger ningun dato de la url");
            }
 
            return null;
        }
 
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Descartar el diálogo de progreso
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * actualizar datos JSON parseados en el ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, menuList,
                    R.layout.drawer_list_item, new String[] { TAG_TITLE}, new int[] { R.id.title});
 
            setListAdapter(adapter);
        }
    }
}
